<?php

namespace Modules\Car\Http\Controllers\Api;

use App\Events\NotifyEvent;
use App\Events\RecivedCarEvent;
use App\Helpers\PayTrait;
use App\Helpers\ResponseData;
use App\Models\Car;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Illuminate\Support\Facades\DB;
use Modules\Car\Entities\CarOrder;
use Modules\Car\Entities\RecognizeDrivingLicense;
use Modules\Car\Http\Requests\Order\OrderRequest;

//待送车订单
class PickOrderController extends Controller
{
    use ResponseData,PayTrait;

    /**
     * 获取排车数量
     */
    public function panel(Request $request){
        $user = $request->user();
        $order_num = CarOrder::query()
            ->where('status',2)->count();
//        $data['send'] = $this->getCarStatus(6)+$order_num+$this->getCarStatus(7);
        $data['send']['waitting'] = $order_num;
        $data['send']['picking'] = $this->getCarStatus(6);
        $data['send']['finish'] = $this->getCarStatus(7);

        //待取车
        $return_order_num = CarOrder::query()
            ->where('status',6)
            ->where('process_status',1)
            ->count();
        //取车中
        $returning = CarOrder::query()
            ->where('status',6)
            ->where('process_status',2)
            ->count();
//        $data['return'] = $return_order_num+$returning;
        $data['return']['waitting'] =  $return_order_num;
        $data['return']['picking'] =  $returning;

        return $this->success($data);
    }
    protected function getCarStatus($status){
        return RecognizeDrivingLicense::query()
            ->where('use_status',$status)
            ->where('is_used',1)->count();
    }
    /**
     * 获取不同车辆状态
     * @param Request $request
     * @return mixed
     */
    public function list(Request $request){
        $size = $request->input('size',10);
        $data = CarOrder::query()
            ->with('user')
            ->where('status',2)
            ->paginate($size);
        return $this->success($data);
    }
    public function edit(OrderRequest $request){
        $data = CarOrder::query()
            ->where('order_sn',$request->order_sn)
            ->where('process_status','>=',1)
            ->where('process_status','<=',3)
            ->first();
        return $this->success($data);
    }
    //获取待排车车辆
    protected function getSeries(){
        return DB::table('cars')
            ->select('cars.id','cars.name','r.id as rid','r.plate_number','r.car_series_id','r.is_used')
            ->leftJoin('recognize_driving_licenses as r', 'cars.id', '=', 'r.car_series_id')
            ->where('r.is_used',0);
    }
    protected function getArray($data){
        if(count($data)>0){
            foreach ($data as $k=>$v){
                $map[$v->id]['id']= $v->id;
                $map[$v->id]['name']= $v->name;
                $map[$v->id]['car'][]= [
                    'id'=>$v->rid,
                    'plate_number'=>$v->plate_number,
                    'car_series_id'=>$v->car_series_id,
                    'is_used'=>$v->is_used
                ];
            }
            $array = array_values($map);
            return $array;
        }

    }
//    获取本车系和其它车系列表
    public function chooseCar(OrderRequest $request){

        $model = $this->getSeries();
        $data['order_sn'] = $request->order_sn;
        $local =  $model->where('cars.id',$request->car_series_id)->get();
        $data['local'] = $this->getArray($local);
        $clone = $this->getSeries();
        $others = $clone->where('cars.id','<>',$request->car_series_id)->get();
        $data['other'] = $this->getArray($others);

        return $this->success($data);
    }

    /**
     * @param OrderRequest $request
     * @return mixed
     * 确定接单 status=3 待送车
     */
    public function confirmOrder(OrderRequest $request){
        // $user = $request->user();
        $order = CarOrder::query()
            ->select('id','pre_fetch_time','pre_return_time','gear_car_id')
            ->first();
        if(!$order){
            return $this->failed('订单不存在',201);
        }
        // 超管也可以操作，这里限制取消
        // if(!$user->phone||!$user->nick_name){
        //     return $this->failed('您还没有绑定手机或者昵称',201);
        // }
        if(!$request->filled('gear_car_id')||!$request->filled('car_series_id')){
            return $this->failed('车辆或车系id为必填项',201);
        }
        DB::beginTransaction();
        //更新车辆
        $data = DB::update('update car_orders set license = ?, status = ?,gear_car_id=? ,car_series_id = ? ,process_status = ? WHERE  status = ? AND order_sn = ?',
            [$request->license,5,$request->gear_car_id,$request->car_series_id,1,2,$request->order_sn]);
        if($data){
            //更新车辆使用状态
            DB::update('UPDATE recognize_driving_licenses set use_status = ?,is_used = ? WHERE id = ?',[6,1,$request->gear_car_id]);
            // $res = DB::update('UPDATE recognize_driving_licenses set use_status = ?,is_used = ? WHERE id = ? AND is_used = ?',[6,1,$request->gear_car_id,0]);
        //    if(!$res){
        //        DB::rollBack();
        //        return $this->failed('很遗憾！手慢了，该车为不可租状态,请换一辆吧！',201);
        //    }
           //设置车辆禁止被其它用户使用
            $this->forbidDate($order->pre_fetch_time,$order->pre_return_time,$request->gear_car_id,$status=1,$request->car_series_id);
            DB::commit();
           // event(new NotifyEvent($order,config('wechat.notify.mini.ConfirmOrder')));
            // 出车统计事件
            event(new RecivedCarEvent($order));
            return $this->success('恭喜!接单成功');
        } else{
            DB::rollBack();
            return $this->failed('来晚咯！订单已经被别人接走了',201);
        }
    }

    /**
     * @param OrderRequest $request
     * @return mixed
     * 送车中
     * 上传送车照片
     *
     * status=4
     */
    public function update(OrderRequest $request){
        $order = CarOrder::query()
            ->select('id','gear_car_id')
            ->where('status',3)
            ->where('order_sn',$request->order_sn)
            ->first();
        if($order){
            $order->send_car_photo = $request->send_car_photo;
            $order->status = 4;
            $order->fact_send_at = now();
            $order->send_over_time = $this->isWorkOvertime();//加班y
            $this->car($order->gear_car_id);
            $order->save();
            event(new NotifyEvent($order,config('wechat.notify.mini.SendPhoto')));
            return $this->success('保存成功，等待送车');
        }else{
            return $this->failed('订单不存在',201);
        }
    }
    protected function car($gear_car_id){
        RecognizeDrivingLicense::query()
            ->where('id',$gear_car_id)
            ->where('use_status',6)
            ->update(['use_status'=>7]);
    }

}
